﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Reflection;
using System.Linq;

namespace Sailfish
{
    public class JsonGUIClass : JsonGUIField
    {
        bool isShow = false;

        Dictionary<FieldInfo, JsonGUIField> fieldGUIInfos = new Dictionary<FieldInfo, JsonGUIField>();

        public JsonGUIClass(Type type, object value, string name) : base(type, value, name)
        {
            var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);

            fieldGUIInfos.Clear();
            foreach (var field in fields)
            {
                var layout = field.GetCustomAttribute<JsonLayoutAttribute>();
                var title  = field.GetCustomAttribute<JsonFieldTitleAttribute>();
                var fieldInfo = Create(layout, field.FieldType, field.GetValue(value), field.Name);
                fieldInfo.FieldTipLayout(title);
                fieldGUIInfos.Add(field, fieldInfo);
            }
        }

    
        public override void TitleLayout()
        {
            isShow = JsonGUILayout.Fold(isShow, name);
        }

        public override void ValueLayout()
        {
            GUILayout.BeginHorizontal();
            GUILayout.Space(60);

            if (isShow)
            {
                GUILayout.BeginVertical();
                foreach (var guiInfo in fieldGUIInfos)
                {
                    guiInfo.Value.value = guiInfo.Key.GetValue(value);
                    guiInfo.Value.HeaderLayout();
                    guiInfo.Value.CustomGUI();
                    guiInfo.Key.SetValue(value, guiInfo.Value.value);
                }
                GUILayout.EndVertical();
            }

            GUILayout.EndHorizontal();
        }
    }
}